<?php
namespace MyAdmin\Controller;

use Think\Controller;

class HelpsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index()
  {
    $helps = M('helps')->where("app_id={$this->app_id}")->order("orderby asc")->select();

    foreach ($helps as $key => &$value) {
      $value['created_at'] = local_time($value['created_at']);
      $value['updated_at'] = local_time($value['updated_at']);

      switch ($value['status']) {
      case 1:
        $value['status_str'] = "开启";
        break;
      case 2:
        $value['status_str'] = "关闭";
        break;
      default:
        $value['status_str'] = "未知";
        break;
      }
    }

    $this->assign("helps", $helps);
    $this->display();
  }

  public function add()
  {
    $this->display();
  }

  public function save()
  {
    $data = I('post.');

    $data['app_id'] = $this->app_id;
    $data['created_at'] = $data['updated_at'] = $this->now_time;
    $data['status'] = 1;
    $data = M('helps')->create($data);
    $result = M('helps')->add($data);

    if ($result) {
      $this->success('操作成功', U('helps/index'));
    } else {
      $this->error('操作失败');
    }
  }

  public function edit()
  {
    $id = I('id');
    $help = M('helps')->where("id=$id")->find();

    $this->assign("help", $help);
    $this->display();
  }

  public function update()
  {
    $data = I('post.');

    $data['updated_at'] = $this->now_time;
    $result = M('helps')->where("id=$data[id]")->save($data);

    if ($result) {
      $this->success('操作成功', U('helps/index'));
    } else {
      $this->error('操作失败');
    }
  }

  public function delete()
  {
    $id = I('id');
    $result = M('helps')->where("id=$id")->delete();

    if ($result) {
      $this->success('操作成功', U('helps/index'));
    } else {
      $this->error('操作失败');
    }
  }

  //改变状态
  public function change_status()
  {
    $model = M("helps");
    $status = I("status", 2);
    $id = I("id", '');

    $post_data["status"] = $status;
    $post_data["updated_at"] = $this->now_time;
    $where = " id=".$id;

    $result = $model->where($where)->save($post_data);
    if ($result) {
      $this->success('操作成功');
    } else {
      $this->error('操作失败');
    }
  }
}
